import React, {
  createRef
} from "react";
import {
  Space,
  Row,
  Table,
  Pagination,
  Typography,
  Button,
  message,
  Select,
  Form,
  Input,
  Modal
} from "antd";
import "./index.less";
import { listClient, createClient } from "@/services/client";
import { PageContainer } from "@ant-design/pro-layout";

const { TextArea } = Input;
const { Option } = Select;

// 登录的路由组件
class Client extends React.Component {
  // 表格规则定义
  columns = [
    {
      title: "客户名称",
      dataIndex: "cusName",
    },
    {
      title: "联系方式",
      dataIndex: "cusPhone",
      render: (value) => {
        const newValue = `${value}`;
        return (
          <p>
            {newValue.substring(0, 3)}
            ****
            {newValue.substring(7, 11)}
          </p>
        );
      }
    },
    {
      title: "品牌",
      dataIndex: "cusBrand",
      //   render: (text, record) => (
      //       Text.join(',')
      //   )
    },
    {
      title: "星级",
      dataIndex: "cusStar",
    },
    {
      title: "折扣",
      dataIndex: "cusDiscount",
    },
    {
      title: "历史订单",
      dataIndex: "cusOrder",
    },
    {
      title: "备注",
      dataIndex: "cusMemo",
      render: (value) => value || "-",
    },
    {
      title: "操作",
      dataIndex: "make",
      render: (text, record) => (
        <Space size="middle">
          <a onClick={this.editClient.bind(this, record)}>编辑</a>
          <a onClick={this.deleteAlert.bind(this, record)}>删除</a>
        </Space>
      )
    }
  ];

   // 手机选择
   CustProPhoneOptions = (
     <Form.Item noStyle>
       <Select style={{ width: 70 }} disabled="disable" placeholder="+86" />
     </Form.Item>
  )

  // 星级选择
  CustStarOptions = (
    <Form.Item name="cusStar" noStyle>
      {/* 加括号报错：刷新时调用函数，但是change时不会调用方法 */}
      <Select style={{ width: 90 }} placeholder="请选择" onChange={this.changeDiscount}>
        <Option value="1">1星</Option>
        <Option value="2">2星</Option>
        <Option value="3">3星</Option>
        <Option value="普通">普通</Option>
      </Select>
    </Form.Item>
  )

    // 表格
    rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          rowData: selectedRows,
        });
      },
      getCheckboxProps: (record) => ({
        name: record.name,
      }),
    };

    constructor(props) {
      super(props);

      this.state = {
        total: 0,
        currentPage: 1,
        size: 10,
        dataSource: [],
        query: 0,
        // isReady: false,
        clientFormModalVisible: false,
        make: "",
        makeMessage: "",
        rowData: [],
        deleteFormModalVisible: false,
        deleteData: [],
      };

      this.searchFormRef = createRef();
      this.ClientFormRef = createRef();
      this.tableWrapperRef = createRef();
      this.otherHeight = 0;
    }

    // 加载table
    componentDidMount() {
      this.fetchTableData()
    }

  // 页码改变时
  handlePageChange = (page, size) => {
    this.setState({ currentPage: page, size }, this.fetchTableData);
  };

  // 新建弹窗开关
  createClient = () => {
    this.setState({
      clientFormModalVisible: true,
      make: "新建客户",
      makeMessage: "创建"
    });
    setTimeout(() => {
      const { setFieldsValue } = this.ClientFormRef.current;
      setFieldsValue({
        // 设置from中item的name值
        cusName: null,
        cusPhone: null,
        cusBrand: null,
        cusStar: null,
        cusAddress: null,
        cusMemo: null,
        cusPro: null,
        cusDiscount: null,
      });
    }, 100);
  };

  // 编辑弹窗开关
  editClient = (a) => {
    this.setState({
      clientFormModalVisible: true,
      make: "编辑客户",
      makeMessage: "修改"
    });
    // 报错：TypeError: Cannot read property ‘setFieldsValue’ of null
    // 原因：对话框模块还没显示，也就是表单还没挂载就调用了setFieldsValue，所以报错
    // 设置定时器延迟解决
    setTimeout(() => {
      const { setFieldsValue } = this.ClientFormRef.current;
      setFieldsValue({
        cusName: a.cusName,
        cusPhone: a.cusPhone,
        cusDiscount: `折扣 ${a.cusDiscount}`,
        cusBrand: a.cusBrand.replace(/,/g, "\n"),
        cusStar: a.cusStar,
        cusAddress: a.cusAddress,
        cusMemo: a.cusMemo,
      });
    }, 100);
  };

  deleteAlert = (a) => {
    const { rowData } = this.state;
    if (a) {
      this.setState({
        deleteData: a,
        deleteFormModalVisible: true
      });
    } else if (rowData.length !== 0) {
      this.setState({
        deleteData: rowData,
        deleteFormModalVisible: true,
      });
    } else {
      message.error("未选中删除信息");
    }
  };

  deleteClients = () => {
    const { deleteData } = this.state;
    // 新建服务器函数，暂放
    createClient({
      data: { deleteData }
    }).then((Res) => {
      if (Res.data.ret === 0) {
        // 删除成功
        message.success("删除成功！");
        // 关闭弹窗
        this.setState({
          deleteFormModalVisible: false
        });
        this.fetchTableData();
      } else {
        // 删除失败
        message.error("删除失败");
      }
    });
  };

  // 重置对应输入框
  resetFliter = () => {
    const { resetFields } = this.searchFormRef.current;
    resetFields();
  };

  // 查询对应函数
  search = () => {
    this.fetchTableData();
  };

  // 对应折扣变化
  changeDiscount=(value) => {
    switch (value) {
      case "1":
        this.ClientFormRef.current.setFieldsValue({
          cusDiscount: '预设折扣 90%',
        });
        break;

      case "2":
        this.ClientFormRef.current.setFieldsValue({
          cusDiscount: '预设折扣 80%',
        });
        break;

      case "3":
        this.ClientFormRef.current.setFieldsValue({
          cusDiscount: '预设折扣 70%',
        });
        break;

      case '普通':
        this.ClientFormRef.current.setFieldsValue({
          cusDiscount: '预设折扣 无',
        });
        break;

      default:
    }
  }

  // 获取输入框信息
  getSearchFormValue = () => {
    const { getFieldsValue } = this.searchFormRef.current;
    const { cusName, cusPhone } = getFieldsValue();
    return { cusName, cusPhone };
  };

  // 获取表格中部分信息,编辑功能中使用
  getClientFormValue = () => {
    const { getFieldsValue } = this.ClientFormRef.current;
    const {
      cusName, cusPhone, cusBrand, cusStar, cusAddress, cusMemo, id
    } = getFieldsValue();
    return {
      cusName, cusPhone, cusBrand, cusStar, cusAddress, cusMemo, id
    };
  };

  // 新建/编辑客户发送服务端请求
  handleSaveClientInfo = () => {
    const {
      cusName,
      cusPhone,
      cusDiscount,
      cusBrand,
      cusStar,
      cusAddress,
      cusMemo,
      id
    } = this.getClientFormValue();
    createClient({
      cusName,
      cusPhone,
      cusBrand: cusBrand + ''.split('\n'),
      cusStar,
      cusAddress,
      cusMemo,
      cusDiscount,
      id
    }).then((ClientRes) => {
      const { makeMessage } = this.state;
      if (ClientRes.data.ret === 0) {
        message.success(`${makeMessage}成功！`);
        this.setState({
          // 关闭新建弹窗
          clientFormModalVisible: false
        });
      } else {
        message.success(`${makeMessage}失败`);
      }
    });
  };

  // 刷新数据
  fetchTableData = async () => {
    const { size, currentPage } = this.state;
    const { cusName, cusPhone } = this.getSearchFormValue();

    const {
      data: { ret },
      data: {
        data: { list, total, query }
      }
    } = await listClient({
      size,
      page: currentPage,
      cusName,
      cusPhone,
    });

    if (ret !== 0) {
      return;
    }
    this.setState({ total, dataSource: list, query });
  };

  // 编辑/新建弹窗样式
  renderClientFormModal = () => {
    const { make, clientFormModalVisible } = this.state;
    return (
      <Modal
        centered
        title={make}
        visible={clientFormModalVisible}
        onOk={() => this.handleSaveClientInfo()}
        onCancel={() => this.setState({ clientFormModalVisible: false })}
      >
        <Form
          ref={this.ClientFormRef}

        >
          <Form.Item
            name="cusName"
            label="客户名称："
            rules={[{ required: true, message: "请输入客户名称" }]}
          >
            <Input placeholder="请输入"/>
          </Form.Item>
          <Form.Item
            name="cusPhone"
            label="联系方式："
            rules={[{ required: true, message: "请输入联系方式" }]}
          >
            <Input addonBefore={this.CustProPhoneOptions} />
          </Form.Item>
          <Form.Item
            name="cusBrand"
            label="品牌："
            rules={[{ required: true, message: "请选择品牌" }]}
            extra="输入品牌名称（每行一个）"
          >
            <TextArea placeholder="请输入品牌值" rows={3}  />
          </Form.Item>
          <Form.Item
            name="cusDiscount"
            label="客户星级："
            rules={[{ required: true, message: "请输入联系方式" }]}
          >
            <Input
              disabled="disabled"
              placeholder="预设折扣 无"
              addonBefore={this.CustStarOptions}
              style={{ width: 200 }}
            />
          </Form.Item>
          <Form.Item name="cusAddress" label="门店地址：">
            <TextArea placeholder="请输入" rows={2} />
          </Form.Item>
          <Form.Item name="cusMemo" label="备注：">
            <TextArea placeholder="请输入备注" style={{ width: 200 }} />
          </Form.Item>
        </Form>
      </Modal>
    );
  };

  // 打开删除弹窗
  showModal = () => {
    this.setState({
      deleteFormModalVisible: true
    });
  };

  // 关闭删除弹窗
  hideModal = () => {
    this.setState({
      deleteFormModalVisible: false
    });
  };

  // 删除弹窗样式
  deleteClientFormModal = () => {
    const { deleteFormModalVisible } = this.state;
    return (
      <Modal
        title="重要提醒"
        visible={deleteFormModalVisible}
        onOk={this.deleteClients}
        onCancel={this.hideModal}
        okText="确认"
        cancelText="取消"
      >
        <p>您正在删除当前选中的内容，删除无法撤销，您确认吗？</p>
      </Modal>
    )
  }

  render() {
    const {
      total, dataSource, currentPage, size, query
    } = this.state;
    return (
    <PageContainer>
      <div className="Adminer">
        <div className="AdminerSearch">
          <div className="AdminerTitle">
            <h2>
              客户管理
              <div className="blank" />
            </h2>
          </div>
          <Form ref={this.searchFormRef}>
            <Form.Item label="客户名称：" className="account" name="cusName">
              <Input placeholder="请输入" />
            </Form.Item>
            <Form.Item label="联系方式：" className="tenant" name="cusPhone">
              <Input placeholder="请输入" />
            </Form.Item>
            <Form.Item className="return">
              <Button type="ghost" onClick={() => this.resetFliter()}>
                重置
              </Button>
            </Form.Item>
            <Form.Item className="search">
              <Button type="primary" onClick={() => this.search()}>
                查询
              </Button>
            </Form.Item>
          </Form>
        </div>

        <div className="AdminerList">
          <p>客户列表</p>
          <Form>
            <Form.Item className="AllDelete">
              <Button type="ghost" onClick={() => this.deleteAlert()}>
                批量删除
              </Button>
            </Form.Item>
            <Form.Item className="add">
              <Button type="primary" onClick={() => this.createClient()}>
                +新建
              </Button>
            </Form.Item>
          </Form>
          <Table
            rowSelection={this.rowSelection}
            pagination={false}
            // loading={!isReady}
            columns={this.columns}
            dataSource={dataSource}
          />
          <Row justify="space-between" align="middle">
            <Typography.Text>
              共
              {query}
              条记录 第
              {currentPage}
              /
              {' '}
              {Math.ceil(query / size) || 1}
              页
            </Typography.Text>

            <Pagination
              showQuickJumper
              showLessItems
              total={total}
              pageSize={10}
              current={currentPage}
              showSizeChanger={false}
              onChange={this.handlePageChange}
            />
          </Row>
        </div>
        {this.renderClientFormModal()}
        {this.deleteClientFormModal()}
      </div>
    </PageContainer>
    );
  }
}

export default Client;
